<template>
    <div class = 'add'>
        <h2 class="tit">医生工作组新增</h2>     
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="110" label-position="left" >
            <div class = 'main'>
                <p class="title">基本信息</p>
                <Row class="box">
                    <Col span="10">
                        <fourLevelLinkage
                            @changeProvince="changeProvince"
                            @changeCity="changeCity"
                            @changeArea="changeArea"
                            @changeHospital="changeHospital"
                            :province="province"
                            :city="city"
                            :area="area"
                            :hospital="hospital"
                            :isBack="isBack"
                            class="botm"
                        ></fourLevelLinkage>
                        <!-- 医疗团队名称 -->
                        <FormItem prop="name" label='医疗团队名称：' class="hongdian">
                            <Input v-model.trim="formValidate.name" placeholder="请输入医疗团队名称" maxlength="20" class="inputbox"></Input>
                        </FormItem>
                        <!-- 允许居民主动在线申请签约 -->
                        <FormItem label='允许居民主动在线申请签约：' :label-width="170" v-if="formValidate.medicalType == 1">
                            <iSwitch size="large"  v-model="formValidate.patientOnOff" >
                                <span slot="open">开通</span>
                                <span slot="close">关闭</span>
                            </iSwitch>
                        </FormItem>
                    </Col>
                    <Col span="7">
                        <!-- 所属科室 -->
                        <div class="suojin botm">
                            <span>所属科室:</span>                       
                            <Select
                                v-model="info.depantmentName"
                                @on-open-change='handleSearch1'
                                placeholder="查询院内科室"
                                class="deptbox" transfer="true">
                                <Option
                                    v-for="item in departmentList"
                                    :value="item.dictName"
                                    :key="item.dictType"
                                >{{item.dictName}}</Option>
                                <!-- <Option
                                    v-for="item in departmentList"
                                    :value="item.deptNickname"
                                    :key="item.dictType"
                                >{{item.deptNickname}}</Option> -->
                            </Select>
                        </div>
                        <!-- 医疗团队电话 -->
                        <FormItem prop="phone" label='医疗团队电话：'>
                            <Input v-model.trim="formValidate.phone"  maxlength="15" placeholder="请输入医疗团队电话" class="inputbox"></Input>
                        </FormItem>
                    </Col>
                    <Col span="7">
                        <!-- 医疗团队类型 -->
                        <FormItem prop="medicalType" label='医疗团队类型：'>
                            <Select placeholder="请选择医疗团队类型"  v-model="formValidate.medicalType" @on-change='changeMedicalType'>
                                <Option
                                    v-for="item in medicalList"
                                    :value="item.id"
                                    :key="item.id"
                                    class="optbox"
                                >{{item.name}}</Option>
                            </Select>
                        </FormItem>
                        <FormItem label='团队图标：' :label-width="80" class="suojin">
                            <div class="input">
                                <div class="demo-upload-list" v-for="item in uploadList">
                                    <div v-if="item.status === 'finished'">
                                        <img :src="item.url">
                                        <div class="demo-upload-list-cover">
                                            <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                                            <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                                        </div>
                                    </div>
                                    <div v-else>
                                        <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                                    </div>
                                </div>
                                <Upload
                                    v-show="uploadList.length==0"
                                    ref="upload"
                                    :show-upload-list="false"
                                    :default-file-list="defaultList"
                                    :on-success="handleSuccess"
                                    :format="['jpg','jpeg','png']"
                                    :max-size="1024"
                                    :on-format-error="handleFormatError"
                                    :on-exceeded-size="handleMaxSize"
                                    :before-upload="handleBeforeUpload"
                                    multiple
                                    type="drag"
                                    :action="uploadUrl"
                                    :headers="fromData"
                                    :data="uploadData"
                                    class="picbox"
                                    
                                >
                                <!-- v-if="!this.fileList" -->
                                    <div class="pic">
                                        <Icon type="ios-camera" size="20"></Icon>
                                    </div>
                                </Upload>
                                <Modal title="预览图片" v-model="visible" footer-hide>
                                    <img :src=" uploadList[0].url " v-if="visible" style="width:100%;height:auto;margin:0 auto;text-algin:center;">
                                </Modal>
                            </div>
                        </FormItem>
                        <div class="tishi">
                            <small>（备注：图片支持.jpg、.jpeg、.png格式,大小不超过1024kb）</small>
                        </div>
                    </Col>
                </Row>
            </div>
            <div class = 'main'>
                <p class="title">团队介绍</p>
                <Row class="box">               
                    <Col span="24">
                        <!-- 医疗团队备注 -->
                        <FormItem label='医疗团队介绍信息：' :label-width="120">
                            <Input maxlength="200"
                                v-model="formValidate.remarks"
                                type="textarea"
                                :rows="6"
                                placeholder="请输入医疗团队介绍信息"
                                class="bigpic"
                            />
                        </FormItem>
                        <!-- 团队管理范围 -->
                        <FormItem label='医疗团队管理范围：' :label-width="120">
                            <Input maxlength="100"
                                v-model="formValidate.teamControlLimi"
                                type="textarea"
                                :rows="6"
                                placeholder="请输入团队管理范围"
                                class="bigpic"
                            />
                        </FormItem>
                    </Col>
                </Row>
            </div>
        </Form>
        <div class = 'main'>
            <p class="title">团队成员</p>
            <!-- 排序 -->
            <div class = 'footerList'>
                <div class="left">
                    <p>可以选择的医疗团队成员</p>
                    <div class="botm youyi" >
                        <Input v-model.trim="searchKey" placeholder="请输入医生名称关键字" class="inputname"></Input>
                        <Button type="primary" icon="ios-search" @click='search'></Button>
                    </div>
                    <Table stripe :columns="member" :data="memberDate"></Table>
                    <Page :total="count"  :page-size='pageSize' :current = 'pageNo'  @on-change='pageChange' class="page"/>
                    <p class="word">查询出医生信息后，点击添加，在右侧的列表显示</p>
                </div>
                <div class="right">
                    <p>已经添加的医疗团队成员</p>
                    <div class="botms">
                        <br>
                    </div>
                    <Table stripe :columns="addMember" :data="addMemberDate"></Table>
                    <p class="word">团队角色必须有团队负责人，并且只能有一个团队负责人</p>
                </div>
            </div>
        </div>
        <div class="butbox">
            <Button type="primary" @click='save("formValidate")' class="btn">
                <Icon type="ios-checkmark" class="icon"/>提交
            </Button>
            <Button @click='reback' class="btn">
                <i class = "iconfont icon-butongyi icon"></i> 取消
            </Button>
        </div>
    </div>
</template>
<script>
import api from "@/api/commonApi";
import code from "@/configs/base.js";
import fourLevelLinkage from "@/components/fourLevelLinkage";
export default {
    components:{
        fourLevelLinkage
    },
    data () {
        return {
            province: null,
            city: null,
            area: null,
            hospital: null,
            isBack: 1,           
            // 所选科室
            info:{
                depantmentName:"",
                depantment:""
            },
            // 科室列表
            departmentList:[],
            // 医疗团队类型
            medicalList:[
                {
                    id:'1',
                    name:"家医签约团队"
                },
                {
                    id:'2',
                    name:"出院随访签约团队"
                }
            ],
            // 所选数据
            formValidate:{
                // 医疗团队名称
                name:"",
                // 医疗团队类型
                medicalType:"",
                // 医疗团队电话
                phone:"",
                // 排序
                sort:"",
                // 备注
                remarks:"",
                patientOnOff:0,
                // 团队管理范围
                teamControlLimi:"",
                patientOnOff:false,
            },
            // 限制条件
            ruleValidate:{
                // 名称
                name:[
					{
						// 是否校验
						required: true,
						// 提示文字
						message: "请输入医疗团队名称",
						// 触发事件
						trigger: "blur"
					}
                ],
                // 类型
                medicalType:[
					{
						required: true,
						message: "请选择医疗团队类型",
						trigger: "change"
					}
                ],
                // 电话
                phone:[
					{
						// 是否校验
						required: true,
						// 提示文字
						message: "请输入医疗团队电话",
						// 触发事件
						trigger: "blur"
					}
                ],
            },
            // 医生查询条件
            searchKey:"",
            // 医生权限管理分页
            pageNo:1,
            pageSize:8,
            count:10,
            // 左侧医疗团队成员
            member:[
                {
                    title:"排序",
                    align:"center",
                    key:"sum"
                },
                {
                    title:"医生姓名",
                    align:"center",
                    key:"doctorName"
                },
                {
                    title:"科室",
                    align:"center",
                    key:"deptName"
                },
                {
                    title:"职称",
                    align:"center",
                    key:"titleName"
                },
                {
                    title:"联系电话",
                    align:"center",
                    key:"phone"
                },
                {
                    title:"设置",
                    align:"center",
                    render:(h,params) => {
                        let row = params.row;
                        return [
                            h('a', {
                                on:{
                                    'click':() => {
                                        this.addMemberDate.push(row)
                                        this.memberDate.splice(row._index,1);
                                        this.roleList[0].disabled = this.disabledRole()
                                    }
                                }
                            }, '添加')
                        ]
                    }
                }
            ],
            memberDate:[],
            roleList:[],
            // 角色列表
            roleList1:[
                // {
                //     id:"0",
                //     name:"其他",
                //     disabled:false
                // },
                {
                    id:"1",
                    name:"团队负责人",
                    disabled:false
                },
                {
                    id:"2",
                    name:"全科医生",
                    disabled:false
                },
                {
                    id:"3",
                    name:"护士",
                    disabled:false
                },
                {
                    id:"4",
                    name:"村医",
                    disabled:false
                },
            ],
            roleList2: [
                {
                    id:"1",
                    name:"团队负责人",
                    disabled:false
                },
                {
                    id:"0",
                    name:"其他",
                    disabled:false
                },
            ],
            // 右侧医疗团队成员
            addMember:[
                {
                    title:"排序",
                    align:"center",
                    key:"sum"
                },
                {
                    title:"医生姓名",
                    align:"center",
                    key:"doctorName"
                },
                {
                    title:"科室",
                    align:"center",
                    key:"deptName"
                },
                {
                    title:"职称",
                    align:"center",
                    key:"titleName"
                },
                {
                    title:"联系电话",
                    align:"center",
                    key:"phone"
                },
                {
                    title:"团队角色",
                    align:"center",
                    width:120,
                    render: (h, params) => {
                            return h('Select', {
                                    props:{
                                    // 监听的值
                                        value: params.row.role,
                                    },
                                    on: {
                                        // 事件触发
                                        'on-change':(event) => {
                                            this.addMemberDate[params.row._index].role = event;
                                            params.row.role = event
                                            this.roleList[0].disabled = this.disabledRole()
                                        }
                                    },
                                },
                                this.roleList.map(function(type){//这个数组需要在data中定义,里面是一个个对象,每个对象里面应当包含value属性(因为要用到)
                                    return h('Option', {
                                        props:{
                                            value:type.id,
                                            disabled:type.disabled
                                        }
                                    }, type.name);
                                })
                            )
                        },
                },
                {
                    title:"设置",
                    align:"center",
                    key:"sum",
                    render:(h,params) => {
                        let row = params.row
                        return [
                            h('a',{
                                on:{
                                    'click':() => {
                                        row.role = ''
                                        this.addMemberDate.splice(row._index,1)
                                        this.memberDate.push(row)
                                        this.roleList[0].disabled = this.disabledRole()
                                    }
                                }

                            },'移除')
                        ]
                    }
                }
            ],
            addMemberDate:[],
            // 上传图标相关
            visible: false,
            uploadList: [],
            defaultList: [],
            uploadModal: true,
            uploadData: { json: '{"urlCode":"' + code.urlCode.doctorGroup + '"}' },
            activeUploadId: "5c2bf345-b973-4ffd-a52e-87bb9c1d2b72",
            uploadUrl: api.fileAll,
            images: "",
            hospitalList: [],
            hospitalName: '',
        }
    },
    created (){
        let breadList = [
            { path: "/index", title: "首页" },
            {
                path: "/index/doctorOperation/doctorGroup/list",
                title: "医生端运营"
            },
            {
                path: "/index/doctorOperation/doctorGroup/list",
                title: "医疗小组"
            }
        ];
        this.$emit("changeBreadList", breadList);
    },
    mounted () {
        this.uploadList = this.$refs.upload.fileList;
        this.findhospital()
    },
    methods:{
        changeProvince(val) {
            this.province = val;
        },
        changeCity(val) {
            this.city = val;
        },
        changeArea(val) {
            this.area = val;
        },
        changeHospital(val) {
            this.hospital = val;
            this.hospitalList.forEach(i =>{
                if (i.id == this.hospital) {
                    this.hospitalName = i.name
                }
            })
            this.info.depantmentName = ''
            if(this.addMemberDate.length) {
                this.addMemberDate = []
            }
        },
        changeMedicalType() {
            if(this.formValidate.medicalType == 1) {
                this.roleList = this.roleList1
            } else if(this.formValidate.medicalType == 2) {
                this.roleList = this.roleList2
            }
        },
        //获取所有医院
        findhospital() {
            var params = {};
            params.hospitalType = 1;
            this.$axios
            .post(api.findKbaoHospitalRegisterDtoPage, params)
            .then(resp => {
                let list = resp.data.object;
                const hospitalList = [];
                list.map((el, i) => {
                    let tmpObj = {};
                    tmpObj.id = parseInt(el.id);
                    tmpObj.name = el.orgName;
                    hospitalList.push(tmpObj);
                });
                this.hospitalList = hospitalList;
            })
            .catch(err => {
                console.log(err);
            });
        },
        // 院内科室
        handleSearch1 (val) {
            if(!Boolean(this.hospital)) {
                this.$Message.error("请先选择医院后再查询科室");
                return ""
            }
            if(Boolean(val)){
                let params = {
                    hospitalId: this.hospital,
                    // pageNo:1,
                    // pageSize: 10,
                    // searchKey:val.trim()
                };
                this.$axios
                    .post(api.findDeptName, params)
                    .then(res => {
                    if (res.data.code) {
                        let ret = res.data.object;
                        this.departmentList = ret
                    }
                }).catch(err => {
                    console.log(err);
                });
            }
            
        },
        // '查询医生权限管理
        search () {
            if(!this.hospital) {
                this.$Message.error("请选择医疗机构")
                return ""
            }
            this.loadDoctorPage(1);
        },
        // 医生权限管理分页器
        pageChange (index) {
            this.loadDoctorPage(index);
        },
        disabledRole(){
            return this.addMemberDate.some(item =>{
                return parseInt(item.role) == 1
            })
        },
        // 医生小组管理-提交 保存
        save (name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    // 医院id
                    if(!Boolean(this.hospital)) {
                        this.$Message.error("请选择医院后再操作")
                        return ""
                    }
                    // 小组成员非空
                    if(!Boolean(this.addMemberDate.length)) {
                        this.$Message.error("请添加小组成员");
                        return ""
                    }
                    // 有且只能有一个队长
                    let team = this.addMemberDate.some(item =>{
                        return parseInt(item.role) == 1
                    })
                    if(!team) {
                        this.$Message.error("请检查团队内是否有团队负责人或存在多个团队负责人")
                        return ""
                    }
                    // 成员角色必须分配
                    let teams = this.addMemberDate.every(item =>{
                        return Boolean(item.role)
                    })
                    if(!teams) {
                        this.$Message.error("请选择团队的成员的角色")
                        return ""
                    }
                    // 成员列表
                    let detailList = []
                    this.addMemberDate.forEach(item =>{
                        detailList.push({
                            doctorId:item.doctorId,
                            doctorName:item.doctorName,
                            deptName:item.deptName,
                            titleName:item.titleName,
                            phone:item.phone,
                            role:item.role
                        })
                    })
                    this.departmentList.forEach(item =>{
                        if(this.info.depantmentName == item.dictName){
                            this.info.depantment = item.dictType
                        }
                    })
                    let params = {
                        "hospitalId":this.hospital,
                        "hospitalName":this.hospitalName,
                        "type":this.formValidate.medicalType,
                        "name":this.formValidate.name,
                        "deptType":this.info.depantment,
                        "deptName":this.info.depantmentName,
                        "phone":this.formValidate.phone,
                        "icon":this.images,
                        "controlLimit":this.formValidate.teamControlLimi,
                        "remark":this.formValidate.remarks,
                        "status":"1",
                        "detailList":detailList,
                        "patientOnOff":Number(this.formValidate.patientOnOff),
                    }
                    this.$axios.post(api.insertTeam,params).then(res => {
                        if(res.data.success) {
                            this.$Message.success("添加成功")
                            setTimeout(()=>{
                                let query = this.$route.query
                                this.functionJS.queryNavgationTo(
                                    this,
                                    "/index/doctorOperation/doctorGroup/list",
                                    {
                                        pageNo:query.pageNo ? parseInt(query.pageNo): 1,
                                        province: query.province ? parseInt(query.province): "",
                                        city: query.city ? parseInt(query.city): "", 
                                        area: query.area ? parseInt(query.area): "",
                                        hospital: query.hospital ? parseInt(query.hospital): "",
                                        isBack: 2
                                    }
                                );
                            },800)
                        } else {
                            this.$Message.error(res.data.message)
                        }
                    }).catch(() => {
                        this.$Message.error(res.data.message)
                    });
                } else {
                    this.$Message.error('请完整填写必款项!');
                }
            })
        },
        // 返回上一页
        reback () {
            let query =this.$route.query
            this.functionJS.queryNavgationTo(
                this,
                "/index/doctorOperation/doctorGroup/list",
                {
                    pageNo:query.pageNo ? parseInt(query.pageNo): 1,
                    province: query.province ? parseInt(query.province): "",
                    city: query.city ? parseInt(query.city): "", 
                    area: query.area ? parseInt(query.area): "",
                    hospital: query.hospital ? parseInt(query.hospital): "",
                    isBack: 2
                }
            );
        },
        // 查询医生权限管理
        loadDoctorPage(pageNo) {
            this.pageNo = pageNo;
            var params = {};
            params.type = 1; // 1医生 2药师 写死。
            params.provinceCode = this.province ? this.province : null;
            params.cityCode = this.city ? this.city : null;
            params.areaCode = this.area ? this.area : null;
            params.hospitalId = this.hospital ? this.hospital : null;
            params.searchKey = this.searchKey.trim();
            params.pageNo = pageNo;
            params.pageSize = this.pageSize;
            this.$axios
                .post(api.doctorAuthlist, params)
                .then(resp => {
                    if (resp.data.success) {
                        this.memberDate = [];
                        this.count = resp.data.object.total;
                        resp.data.object.records.forEach((item,index) => {
                            item.sum = this.addZeros(index)
                            let flag = this.addMemberDate.some(items =>{
                                return parseInt(item.doctorId) == items.doctorId
                            })
                            if (!flag) {
                                this.memberDate.push(item)
                            }
                        })
                        if(!Boolean(this.memberDate.length)) {
                            this.$Message.error("未查询到该医生或已经添加到小组内")
                        }
                    } else {
                        this.$Message.info("不允许访问");
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 上传图相关事件
        handleView(name) {
            this.imgName = name;
            this.visible = true;
        },
        handleRemove(file) {
            const fileList = this.$refs.upload.fileList;
            this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
            if(this.images){
                this.images = ''
            }
        },
        handleSuccess(res, file) {
            console.log(res);
            res = this.uploadFileDecrypt(res);
            file.url = this.fileBaseUrl + res.object[0].fileName;
            this.images = JSON.stringify(res.object[0]);
            file.name = res.object[0].fileName;
        },
        handleFormatError(file) {
            this.$Notice.warning({
                title: "格式错误",
                desc: "文件 " + file.name + " 上传失败,请重试"
            });
        },
        handleMaxSize(file) {
            this.$Notice.warning({
                title: "文件过大",
                desc: `文件${file.name}过大，文件最大限制为1024KB`
            });
        },
        handleBeforeUpload(file) {
            const check = this.uploadList.length < 1;
            if (!check) {
                this.$Message.info("只能上传一张图片");
            }
            return check;
        }
    },
    watch: {
        hospital() {
            this.loadDoctorPage(1);
        }
    }
}
</script>
<style lang="less" scoped>
.demo-upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
}
.demo-upload-list img {
    width: 100%;
    height: 100%;
}
.demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
    display: block;
}
.demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
}
    .add{
        padding: 10px 0;
        width: 100%;
        background: #ffffff;
        box-sizing: border-box;
        .tit {
            margin:10px 0;
            font-weight:bold;
            text-align:center;
        }
        .main{
            width: 98%;
            display: flex;
            flex-direction: column;
            margin: 10px auto;
            border: 1px solid #f0f0f0;
            box-shadow: 0 4px 3px #ebedf8;
            border-radius: 5px;
            margin-bottom: 20px;
            .title {
                font-size: 20px;
                padding-left: 15px;
                margin-bottom: 20px;
                color: #333;
                height: 40px;
                line-height: 40px;
                background: #ebedf8;         
            }
            .box{
                padding: 0 30px;
            }
            .hongdian {
                margin-left: -10px;
            }
            .suojin {
                padding-left: 13px;
            }
            .footerList{
                display:flex;
                flex-direction:row;
                justify-content: space-between;
                margin: 0 30px;
                margin-bottom: 20px;
                .left,.right{
                    display:flex;
                    flex-direction:column;
                    width:48%;
                    border: 1px #ccc solid;
                    p{
                        text-align:center;
                         line-height: 45px;
                    }
                }
            }
            .botm {
                margin-bottom: 20px;
            }
            .youyi {
                margin-left: 40px;
            }
            .inputbox {
                width: 90%;
            }
            .deptbox {
                width: 75%;
            }
            .optbox {
                text-align: center;
            }
            .picbox {
                display: inline-block;
                width: 58px;
            }
            .pic {
                width: 58px;
                height: 58px;
                line-height: 58px;
            }
            .bigpic {
               width: 100%;
            }
            .tishi {
                margin:-30px 0 20px 0;
                color: #ff9966;
            }
            .inputname {
                width: 200px;
            }
            .page {
                margin: 10px 0;
                text-align: center;
            }
            .word {
               color: #ff9966;
            }
            .botms {
                margin-bottom: 30px;
            }
        }
        .butbox {
            text-align: center;
            margin: 20px auto;
            .btn {
                width: 75px;
                height: 35px;
            }
        }
        .icon {
            font-size: 14px;
            margin-right: 5px;
        }
    }
</style>
